package com.doradance.app.curriculum;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.ShareUtil;
import com.doradance.account.utils.XCRoundRectImageView;
import com.doradance.app.home.ClassEvent;
import com.doradance.app.home.CoursesDetailActivity;
import com.doradance.app.home.FreeListAdapter;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.common.http.MyResponseParser;
import com.doradance.entity.FreeItemEntity;
import com.doradance.entity.SelectCurriteEntity;
import com.example.xlhratingbar_lib.XLHRatingBar;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.ListDataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.uuzuche.lib_zxing.decoding.Intents;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class CurriculumListFragment extends SwipeListFragment {
    public static final String KEY_CHANNELID = "CHANNELID";
    private final static int PAGE_SIZE = 10;
    private int lastListSize = 0;
    @InjectExtra(KEY_CHANNELID)
    int mChannelID = 0;
    private int mPage = 0;
    private int mlastid;
    private String difficulty = "";
    private String grade= "";
    private String sort= "";
    private String age= "";
    private Boolean isRefrent =false ;
    private CurriculumAdapter curriculumAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Dart.inject(this, getArguments());
        EventBus.getDefault().register(this);
        clearDecorations();
//        onStartLoading();
    }

    @Override
    public void onResume() {
        super.onResume();
        clearDecorations();
        mPage = 0;
        getData().clear();
        onStartLoading();
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
//        hideRefreshView();
        mPage = 0;
        getData().clear();
        curriculumAdapter.notifyDataSetChanged();
        startLoading();
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        curriculumAdapter = new CurriculumAdapter(getContext());
        return curriculumAdapter;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long itemId) {
        super.onItemClick(arg0, arg1, position, itemId);
        FreeItemEntity o = (FreeItemEntity) getData().get(position);
        CoursesDetailActivity.start(getActivity(),o.getId());
    }

    @Override
    public void onStartLoading() {

        getListData();
    }

    MyResponseParser<FreeItemEntity> parser = new MyResponseParser<FreeItemEntity>(FreeItemEntity.class) {
        @Override
        public boolean hasMore() {
//            if (lastListSize >= PAGE_SIZE) {
            return true;
//            } else {
//                return false;
//            }
        }
    };

    ListDataRequestListener mRequestListener = new ListDataRequestListener(this, parser) {
        @Override
        public void onSuccess(Object listData) {
            super.onSuccess(listData);
            if (getData().size() > 0) {
                mlastid = ((FreeItemEntity) getData().get(getData().size() - 1)).getId();
            }
            List<FreeItemEntity> list = (List<FreeItemEntity>) listData;
            if (list != null) {
                lastListSize = list.size();
            }
            if(sort.equals("learning_count desc")){
                ShareUtil.setIsHot(true);
                ShareUtil.setIsNew(false);
            }else if(sort.equals("create_time desc")){
                ShareUtil.setIsNew(true);
                ShareUtil.setIsHot(false);
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(SelectCurriteEntity refreshEvent){
        difficulty = refreshEvent.difficulty;
        grade = refreshEvent.grade;
        sort = refreshEvent.sort;
        age = refreshEvent.age;
        onStartRefreshing();
    }






    private void getListData() {
        if (mPage == 0 || mRequestListener.getResponseDataParser().hasMore()) {
            mPage++;
            IHttpRequest request = new MyHttpRequest(getContext());
            UrlParams params = new UrlParams();
            params.put("catid", mChannelID + "");
            //以下是筛选 条件
            params.put("ageRangeId", age + "");
            params.put("difficulty", difficulty + "");
            params.put("vipLevel", grade + "");
            params.put("orderby", sort + "");
            params.put("page", mPage + "");
            params.put("size", PAGE_SIZE + "");
            request.get(UrlCenter.COURSES_LIST, params, mRequestListener);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class CurriculumAdapter extends RecyclerViewBaseAdapter<FreeItemEntity> {
        public CurriculumAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.home_recommend));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder viewHolder, int position) {
            VH holder = (VH) viewHolder;
            FreeItemEntity freeItemEntity = getData().get(position);
            holder.mTvRcmdTitle.setText(freeItemEntity.getName());
            holder.mTvRcmdFree.setText(freeItemEntity.getVip_name());
            holder.mTvRcmdTime.setText("训练周期:"+freeItemEntity.getCycle()+"小时");
            holder.mTvRcmdNum.setText(freeItemEntity.getLearning_count()+"人学过");
            holder.mRatingbarId.setCountSelected(freeItemEntity.getDifficulty());
            Glide.with(getContext()).load(freeItemEntity.getCover()).asBitmap().into(holder.mBgIvRcmd);
            holder.mBgIvRcmd.setAlpha(0.7f);
            holder.mIvCollectPlay.setAlpha(0.66f);
        }
    }

    public class VH extends RecyclerView.ViewHolder {
        @Bind(R.id.bg_iv_rcmd)
        XCRoundRectImageView mBgIvRcmd;
        @Bind(R.id.tv_rcmd_title)
        TextView mTvRcmdTitle;
        @Bind(R.id.tv_rcmd_free)
        TextView mTvRcmdFree;
        @Bind(R.id.tv_rcmd_time)
        TextView mTvRcmdTime;
        @Bind(R.id.tv_rcmd_num)
        TextView mTvRcmdNum;
        @Bind(R.id.ratingbarId)
        XLHRatingBar mRatingbarId;
        @Bind(R.id.rl_all)
        RelativeLayout mRlAll;
        @Bind(R.id.iv_collect_play)
        ImageView mIvCollectPlay;

        public VH(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
